package com.zhoug.zmui3.valuepair.align;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zhoug.common3.utils.LogUtils;
import com.zhoug.common3.utils.StringUtils;
import com.zhoug.zmui3.R;
import com.zhoug.zmui3.ZMUIAlignmentTextView;
import com.zhoug.zmui3.utils.ZMUIUtils;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;

/**
 * 键值对水平布局组件父组件
 * ------------------|
 * |我是标签:  我是值  |
 * -------------------
 * zmui_style_ZMUIAbsKeyValueAlignView
 *
 * @Author HK-LJJ
 * @Date 2020/3/23
 * @Description
 */
public abstract class ZMUIAbsKeyValueAlignView<V extends View> extends LinearLayout {
    private static final String TAG = ">>>ZMUIAbsKeyValueAlignView";
    private static final boolean DEBUG = false;
    protected ZMUIAlignmentTextView labelView;
    protected V valueView;
    private TextView errorView;
    protected CharSequence label;
    protected CharSequence value;
    protected float labelSize;//label大小
    protected float valueSize;//value大小
    protected int labelColor;//label颜色
    protected int valueColor;//value颜色
    protected int labelWidth;//
    protected int valueWidth;
    protected float labelWeight;
    protected float valueWeight;

    protected int labelTextAlign=ZMUIAlignmentTextView.GRAVITY_START;
    protected int labelTextEms;
    protected boolean requiredPlaceholder;
    protected boolean colonPlaceholder;
    protected String[] labelWords;

    protected int space;//label和value之间的margin
    protected boolean required;//是否必须
    protected int requiredTagGravity=ZMUIAlignmentTextView.GRAVITY_END;//必须星号标记的位置
    protected boolean enabled;
    protected String hint;
    protected int maxLines;//0:不限制行数,1:singleLine,>1:确定的行数
    protected int inputType;
    protected int maxLength;//值的最大长度
    protected int gravity;//值的对齐方式
    protected CharSequence digits;

    public static final int MATCH_PARENT = -1;
    public static final int WRAP_CONTENT = -2;

    private int paddingLeft;
    private int paddingTop;
    private int paddingRight;
    private int paddingBottom;

    private List<OnValueChangeListener> onValueChangeListeners;
    private String error;


    public ZMUIAbsKeyValueAlignView(Context context) {
        this(context, null);
    }

    public ZMUIAbsKeyValueAlignView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, R.attr.zmui_style_ZMUIAbsKeyValueAlignView);
    }

    public ZMUIAbsKeyValueAlignView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        if (defStyleAttr == 0) {
            defStyleAttr = R.attr.zmui_style_ZMUIAbsKeyValueAlignView;
        }
        parseAttrs(context, attrs, defStyleAttr, R.style.zmui_style_ZMUIAbsKeyValueAlignView);
        init();
    }

    protected void parseAttrs(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ZMUIAbsKeyValueAlignView, defStyleAttr, defStyleRes);
        label = typedArray.getString(R.styleable.ZMUIAbsKeyValueAlignView_zmui_label);
        value = typedArray.getString(R.styleable.ZMUIAbsKeyValueAlignView_zmui_value);
        labelSize = typedArray.getDimension(R.styleable.ZMUIAbsKeyValueAlignView_zmui_labelSize, 0f);
        valueSize = typedArray.getDimension(R.styleable.ZMUIAbsKeyValueAlignView_zmui_valueSize, 0f);
        labelColor = typedArray.getColor(R.styleable.ZMUIAbsKeyValueAlignView_zmui_labelColor, ZMUIUtils.UN_USED_COLOR);
        valueColor = typedArray.getColor(R.styleable.ZMUIAbsKeyValueAlignView_zmui_valueColor, ZMUIUtils.UN_USED_COLOR);

        labelWidth = typedArray.getLayoutDimension(R.styleable.ZMUIAbsKeyValueAlignView_zmui_labelWidth, WRAP_CONTENT);
        valueWidth = typedArray.getLayoutDimension(R.styleable.ZMUIAbsKeyValueAlignView_zmui_valueWidth, WRAP_CONTENT);
        labelWeight = typedArray.getFloat(R.styleable.ZMUIAbsKeyValueAlignView_zmui_labelWeight, 0);
        valueWeight = typedArray.getFloat(R.styleable.ZMUIAbsKeyValueAlignView_zmui_valueWeight, 0);

        space = typedArray.getDimensionPixelOffset(R.styleable.ZMUIAbsKeyValueAlignView_zmui_space, 10);
        required = typedArray.getBoolean(R.styleable.ZMUIAbsKeyValueAlignView_zmui_required, false);
        requiredTagGravity = typedArray.getInt(R.styleable.ZMUIAbsKeyValueAlignView_zmui_requiredTabGravity, ZMUIAlignmentTextView.GRAVITY_END);
        labelTextAlign = typedArray.getInt(R.styleable.ZMUIAbsKeyValueAlignView_zmui_labelTextAlign, ZMUIAlignmentTextView.GRAVITY_START);
        labelTextEms = typedArray.getInt(R.styleable.ZMUIAbsKeyValueAlignView_zmui_labelTextEms, 0);
        requiredPlaceholder = typedArray.getBoolean(R.styleable.ZMUIAbsKeyValueAlignView_zmui_requiredPlaceholder, false);
        colonPlaceholder = typedArray.getBoolean(R.styleable.ZMUIAbsKeyValueAlignView_zmui_colonPlaceholder, false);
        String word = typedArray.getString(R.styleable.ZMUIAbsKeyValueAlignView_zmui_labelWords);
        if (!StringUtils.isNullOrEmpty(word)) {
            labelWords = word.split(",");
        }
        error = typedArray.getString(R.styleable.ZMUIAbsKeyValueAlignView_zmui_error);
        //android 属性
        maxLines = typedArray.getInt(R.styleable.ZMUIAbsKeyValueAlignView_android_maxLines, 1);
        hint = typedArray.getString(R.styleable.ZMUIAbsKeyValueAlignView_android_hint);
        enabled = typedArray.getBoolean(R.styleable.ZMUIAbsKeyValueAlignView_android_enabled, true);
        inputType = typedArray.getInt(R.styleable.ZMUIAbsKeyValueAlignView_android_inputType, -11);
        digits = typedArray.getText(R.styleable.ZMUIAbsKeyValueAlignView_android_digits);
        maxLength = typedArray.getInt(R.styleable.ZMUIAbsKeyValueAlignView_android_maxLength, 0);
        paddingTop = typedArray.getDimensionPixelOffset(R.styleable.ZMUIAbsKeyValueAlignView_android_paddingTop, 0);
        paddingBottom = typedArray.getDimensionPixelOffset(R.styleable.ZMUIAbsKeyValueAlignView_android_paddingBottom, 0);
        paddingLeft = typedArray.getDimensionPixelOffset(R.styleable.ZMUIAbsKeyValueAlignView_android_paddingStart, 0);
        paddingRight = typedArray.getDimensionPixelOffset(R.styleable.ZMUIAbsKeyValueAlignView_android_paddingEnd, 0);
        gravity = typedArray.getInt(R.styleable.ZMUIAbsKeyValueAlignView_android_gravity, Gravity.CENTER);
        Drawable background = typedArray.getDrawable(R.styleable.ZMUIAbsKeyValueAlignView_android_background);
        if (DEBUG) {
            LogUtils.d(TAG, "parseAttrs:paddingTop=" + paddingTop + ",paddingBottom=" + paddingBottom + ",paddingLeft=" + paddingLeft + ",paddingRight=" + paddingRight);
        }
        setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
        if (background != null) {
            setBackground(background);
        }
//        LogUtils.d(TAG, "ValuePairParent:inputType=" + inputType);
//        LogUtils.d(TAG, "ValuePairParent:maxLength=" + maxLength);
        typedArray.recycle();
    }

    protected void init() {
        setOrientation(VERTICAL);
        LinearLayout contentContainer = new LinearLayout(getContext());
        contentContainer.setOrientation(HORIZONTAL);
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        contentContainer.setLayoutParams(params);
        addView(contentContainer);
        //错误提示
        errorView = new TextView(getContext());
        LayoutParams errorParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        errorParams.gravity = Gravity.END;
        errorView.setLayoutParams(errorParams);
        errorView.setGravity(Gravity.END);
        errorView.setTextColor(Color.RED);
        ZMUIUtils.setTextSize(errorView, getContext().getResources().getDimension(R.dimen.zmui_textSize_12));
        addView(errorView);
        setError(error);

        labelView = new ZMUIAlignmentTextView(getContext());
        LayoutParams params1 = new LayoutParams(labelWidth, LayoutParams.WRAP_CONTENT);
        params1.rightMargin = space;
        params1.weight = labelWeight;
        labelView.setLayoutParams(params1);
        contentContainer.addView(labelView, 0);
        initLabel(labelView);

        valueView = getValueView();
        LayoutParams params2 = new LayoutParams(valueWidth, LayoutParams.WRAP_CONTENT);

        params2.weight = valueWeight;
//        params2.leftMargin=space;
        valueView.setLayoutParams(params2);
        if (DEBUG) {
            LogUtils.d(TAG, "init:valueView=" + valueView);
        }
        if (valueView instanceof TextView) {
            if (DEBUG) {
                LogUtils.d(TAG, "init:is textView");
            }
            initValue((TextView) valueView);
        }

        contentContainer.addView(valueView, 1);

    }


    private void addValueView() {

    }

    protected void initLabel(ZMUIAlignmentTextView labelView) {
        ZMUIUtils.setTextSize(labelView, labelSize);
        ZMUIUtils.setTextColor(labelView, labelColor);
        if(labelView!=null){
            labelView.setTextEms(labelTextEms);
            labelView.setTextAlign(labelTextAlign);
            labelView.setRequired(required);
            labelView.setRequiredTabGravity(requiredTagGravity);
            labelView.setRequiredPlaceholder(requiredPlaceholder);
            labelView.setColonPlaceholder(colonPlaceholder);
            labelView.setWords(labelWords);
            labelView.setText(label);
        }
    }

    @Override
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
        getValueView().setEnabled(enabled);
        labelView.setEnabled(enabled);
        if (enabled) {
            _setLabel();
        } else {
            labelView.setText(label);
        }
    }


    public abstract V getValueView();

    public ZMUIAlignmentTextView getLabelView() {
        return labelView;
    }

    public void setHint(String hint) {
        this.hint = hint;
        if (valueView instanceof TextView) {
            ((TextView) valueView).setHint(hint);
        }
    }

    protected void initValue(TextView valueView) {
        if (inputType != -11) {
            valueView.setInputType(inputType);
        }
        valueView.setGravity(gravity);
        if (hint != null) {
            valueView.setHint(hint);
        }
        ZMUIUtils.setTextSize(valueView, valueSize);
        ZMUIUtils.setTextColor(valueView, valueColor);
        valueView.setText(value);
        valueView.setEnabled(enabled);
        if (maxLines == 0) {
            valueView.setSingleLine(false);
        } else if (maxLines > 1) {
            valueView.setSingleLine(false);
            valueView.setMaxLines(maxLines);
        } else {
            valueView.setSingleLine(true);
        }
        if (digits != null) {
            valueView.setKeyListener(DigitsKeyListener.getInstance(digits.toString()));
        }
        if (maxLength > 0) {
            valueView.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
//            valueView.setMaxLines(maxLength);
        }
        valueView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                setError(null);
                onValueChange();
            }
        });
    }

    protected void onValueChange() {
        if (onValueChangeListeners != null && onValueChangeListeners.size() > 0) {
            for (OnValueChangeListener listener : onValueChangeListeners) {
                listener.onChange();
            }
        }
    }


    public void setLabel(CharSequence label) {
        this.label = label;
        if (labelView != null) {
            labelView.setText(label);
        }
    }

    private void _setLabel() {
        if (labelView != null) {
            labelView.setText(label);
        }
    }

    public void addOnValueChangeListener(OnValueChangeListener onValueChangeListener) {
        if (onValueChangeListeners == null) {
            onValueChangeListeners = new ArrayList<>();
        }
        onValueChangeListeners.add(onValueChangeListener);
    }


    public boolean isRequired() {
        return required;
    }

    public void setRequired(boolean required) {
        this.required = required;
    }


    /**
     * 设置错误提示
     *
     * @param error
     */
    public void setError(CharSequence error) {
        if (DEBUG) {
            LogUtils.d(TAG, "setError:error=" + error);
        }
        if (!TextUtils.isEmpty(error)) {
            //显示错误
            if (errorView.getVisibility() != View.VISIBLE) {
                errorView.setVisibility(View.VISIBLE);
            }
            errorView.setText(error);
            int widthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
            int HeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
            errorView.measure(widthMeasureSpec, HeightMeasureSpec);

            int measuredHeight = errorView.getMeasuredHeight();
            int paddingBottom = getPaddingBottom();
            int offBottom = paddingBottom - measuredHeight;
            if (offBottom < 0) {
                offBottom = 0;
            }
            if (DEBUG) {
                LogUtils.d(TAG, "setError:offBottom=" + offBottom);
            }
            setPadding(paddingLeft, paddingTop, paddingRight, offBottom);
        } else {
            //隐藏错误
            if (errorView.getVisibility() == View.VISIBLE) {
                errorView.setVisibility(View.GONE);
                errorView.setText("");
                setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
            }

        }
    }


    public abstract String getValue();

    public abstract void setValue(CharSequence value);


    public interface OnValueChangeListener {
        void onChange();
    }


}
